package org.nanhill.osgi.example.web.impl;

/*
 * RIAWork.org
 * 
 * OSGI Opendoc Demo
 */
import javax.servlet.ServletException;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;
import org.osgi.service.http.HttpService;
import org.osgi.service.http.NamespaceException;

/**
 * desc: 基于传统的方式完成服务的引用和监听
 * 
 * @author jerry
 */
public class Activator implements BundleActivator, ServiceListener {

	// ------------------------------------------------Instance Variables

	private BundleContext bc;

	private ServiceReference ref;

	// ------------------------------------------------Public Method

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
	 */
	public void start(BundleContext context) throws ServletException,
			NamespaceException, InvalidSyntaxException {
		bc = context;
		registerServlet();
		bc.addServiceListener(this, "(objectClass="
				+ HttpService.class.getName() + ")");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
	 */
	public void stop(BundleContext context) {
		unregisterServlet();
		bc = null;
		ref = null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.osgi.framework.ServiceListener#serviceChanged(org.osgi.framework.ServiceEvent)
	 */
	public void serviceChanged(ServiceEvent event) {
		switch (event.getType()) {
		case ServiceEvent.REGISTERED:
			try {
				registerServlet();
			} catch (ServletException e) {
				e.printStackTrace();
			} catch (NamespaceException e) {
				e.printStackTrace();
			}
			break;

		case ServiceEvent.UNREGISTERING:
			unregisterServlet();
			break;
		}
	}

	// ------------------------------------------------Private Method

	/*
	 * 注册Web应用
	 */
	private void registerServlet() throws ServletException, NamespaceException {
		if (ref == null) {
			ref = bc.getServiceReference(HttpService.class.getName());
		}

		if (ref != null) {
			HttpService http = (HttpService) bc.getService(ref);
			http.registerServlet("/login", new LoginServlet(bc), null, null);
			http.registerServlet("/ws/login", new HessianLoginServlet(bc),
					null, null);
			System.out.println("servlet register finish!");
		}
	}

	/*
	 * 卸载Web应用
	 */
	private void unregisterServlet() {
		if (ref != null) {
			HttpService http = (HttpService) bc.getService(ref);
			http.unregister("/login");
			http.unregister("/ws/login");
			System.out.println("servlet unregister finish!");
		}
	}

}
